package com.colin.jipay.weidian;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.colin.jipay.bean.WDShopTransBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;

public class WDShopHelper {
    /**
     * hook订单管理界面被创建的时候
     *
     * @param classLoader
     */
    public static void hookOrderListFragmentOnCreated(ClassLoader classLoader) {
        XposedHelpers.findAndHookMethod("com.koudai.weishop.order.page.list.OrderListFragment"
                , classLoader
                , "onViewCreated"
                , View.class
                , Bundle.class
                , new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        Object objOrderMent = param.thisObject;
                        Object objVp = XposedHelpers.getObjectField(objOrderMent, "viewpager");

                        LogUtils.i("vp的adapter=" + XposedHelpers.callMethod(objVp, "getAdapter").getClass().getName());
                    }
                });
    }

    /**
     * hook 订单管理里面下面的进行中，已完成，已关闭的viewPager在切换界面时候的方法
     *
     * @param classLoader
     */
    public static void hookOrderViewPagerOnChanged(ClassLoader classLoader) {
        XposedHelpers.findAndHookMethod("com.koudai.weishop.order.page.list.OrderListFragment$a"
                , classLoader
                , "instantiateItem"
                , ViewGroup.class
                , int.class
                , new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        LogUtils.i("vp切换界面的时候，切换的对象=" + param.getResult().getClass().getName());
                    }
                });
    }

    /**
     * hook 到订单管理里面的订单数据被点击的时候的方法
     *
     * @param classLoader
     */
    public static void hookOrderListItemOnClick(ClassLoader classLoader) throws Exception {
        XposedHelpers.findAndHookMethod("com.koudai.weishop.order.page.list.tabs.common.OrderListTabCommonViewer"
                , classLoader
                , "a"
                , int.class
                , classLoader.loadClass("com.koudai.weishop.order.page.list.model.OrderListItem")
                , new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                        Object objOrderItem = param.args[1];
                        Object objBuyerInfo = XposedHelpers.callMethod(objOrderItem, "getBuyerInfo");
                        Object objFxSellerInfo = XposedHelpers.callMethod(objOrderItem, "getFxSellerInfo");

                        String buyerId = (String) XposedHelpers.callMethod(objBuyerInfo, "getBuyerId");
                        String buyerName = (String) XposedHelpers.callMethod(objBuyerInfo, "getBuyerName");

                        String fxSellerAddress = (String) XposedHelpers.callMethod(objFxSellerInfo, "getFxSellerAddress");
                        long fxSellerId = (long) XposedHelpers.callMethod(objFxSellerInfo, "getFxSellerId");
                        String fxSellerName = (String) XposedHelpers.callMethod(objFxSellerInfo, "getFxSellerName");

                        String buyerNote = (String) XposedHelpers.callMethod(objOrderItem, "getBuyerNote");
                        String exhibitionJumpUrl = (String) XposedHelpers.callMethod(objOrderItem, "getExhibitionJumpUrl");
                        String expressFee = (String) XposedHelpers.callMethod(objOrderItem, "getExpressFee");
                        String imgHead = (String) XposedHelpers.callMethod(objOrderItem, "getImgHead");
                        int loginSellerRole = (int) XposedHelpers.callMethod(objOrderItem, "getLoginSellerRole");
                        String orderDesc = (String) XposedHelpers.callMethod(objOrderItem, "getOrderDesc");
                        String orderId = (String) XposedHelpers.callMethod(objOrderItem, "getOrderId");
                        int orderSource = (int) XposedHelpers.callMethod(objOrderItem, "getOrderSource");
                        String phoneArgueDesc = (String) XposedHelpers.callMethod(objOrderItem, "getPhoneArgueDesc");
                        String point = (String) XposedHelpers.callMethod(objOrderItem, "getPoint");
                        int quantity = (int) XposedHelpers.callMethod(objOrderItem, "getQuantity");
                        String refundStatusDesc = (String) XposedHelpers.callMethod(objOrderItem, "getRefundStatusDesc");
                        String selFromValue = (String) XposedHelpers.callMethod(objOrderItem, "getSelFromValue");
                        long sellerId = (long) XposedHelpers.callMethod(objOrderItem, "getSellerId");
                        String showTime = (String) XposedHelpers.callMethod(objOrderItem, "getShowTime");
                        int status = (int) XposedHelpers.callMethod(objOrderItem, "getStatus");
                        String statusDesc = (String) XposedHelpers.callMethod(objOrderItem, "getStatusDesc");
                        int statusHighLight = (int) XposedHelpers.callMethod(objOrderItem, "getStatusHighLight");

                        Object subOrderVOList = (Object) XposedHelpers.callMethod(objOrderItem, "getSubOrderVOList");
                        LogUtils.i(XposedHelpers.callMethod(subOrderVOList, "get", 0).getClass().getName());

                        String totalPrice = (String) XposedHelpers.callMethod(objOrderItem, "getTotalPrice");

                        LogUtils.i(buyerNote, exhibitionJumpUrl, expressFee, orderDesc, orderId, showTime, statusDesc);
                    }
                });
    }

    /**
     * hook 到订单管理里面获取到订单数据时候的方法
     *
     * @param classLoader
     */
    public static void hookOrderListGetData(ClassLoader classLoader) {
        XposedHelpers.findAndHookMethod("com.koudai.weishop.order.page.list.tabs.common.OrderListTabCommonViewer"
                , classLoader
                , "a"
                , boolean.class
                , List.class
                , boolean.class
                , new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                        try {
                            List orderList = (List) param.args[1];
                            int listCount = (int) XposedHelpers.callMethod(orderList, "size");
                            if (listCount == 0) {
                                return;
                            }

                            //下面对第一条订单数据进行判断
                            Object objOrderItem = XposedHelpers.callMethod(orderList, "get", 0);
                            String statusDescTemp = (String) XposedHelpers.callMethod(objOrderItem, "getStatusDesc");
                            //如果是待发货的订单才继续读取订单数据
                            if (!statusDescTemp.equals("待发货")) {
                                return;
                            }

                            LogUtils.i("hook 到订单管理里面获取到订单数据时候的方法");

                            String firstOrderId = (String) XposedHelpers.callMethod(objOrderItem, "getOrderId");
                            long firstSellerId = (long) XposedHelpers.callMethod(objOrderItem, "getSellerId");
                            String firstShowTime = (String) XposedHelpers.callMethod(objOrderItem, "getShowTime");

                            @SuppressLint("SimpleDateFormat")
                            long lasShowTimeMilli = TimeUtils.string2Millis(firstShowTime, new SimpleDateFormat("支付时间：yyyy-MM-dd HH:mm:ss"));
//                            SPUtils.getInstance(sellerId + "").put("lastOrderId","");
//                            SPUtils.getInstance(sellerId + "").put("lastShowTime",0);
                            String lastOrderId = SPUtils.getInstance(firstSellerId + "").getString("lastOrderId", "");
                            long lastShowTime = SPUtils.getInstance(firstSellerId + "").getLong("lastShowTime", 0);

                            LogUtils.i(lastShowTime, lastOrderId, lasShowTimeMilli, firstOrderId, firstSellerId);

                            //本地没有保存订单数据，或者数据列表里面的最上面的一条数据id和历史不一致，且这条数据显示的时间比历史保存的时间新。
                            //因为存在两笔订单，时间线在后面的先被发货了。
                            if (lastOrderId.equals("")
                                    || (!lastOrderId.equals(firstOrderId) && lasShowTimeMilli > lastShowTime)) {
                                LogUtils.i("第一条数据和本地保存的不一致，开始保存");
                                SPUtils.getInstance(firstSellerId + "").put("lastOrderId", firstOrderId);
                                SPUtils.getInstance(firstSellerId + "").put("lastShowTime", lasShowTimeMilli);
                                //否则说明第一条数据和本地保存的一致
                            } else {
                                LogUtils.i("第一条数据和本地保存的一致,或本地保存的历史订单时间比第一条数据新");
                                return;
                            }

                            //这个就是新的订单交易数据。
                            List<WDShopTransBean> newWdShopTransBeans = new ArrayList<>();
                            //开始循环读取新订单数据
                            for (int j = 0; j < orderList.size(); j++) {
                                Object orderItem = orderList.get(j);

                                //判断是否有一条数据的订单id和历史订单id一致，或者订单id时间旧于历史订单id,说明新数据读取完了。

                                String orderId = (String) XposedHelpers.callMethod(orderItem, "getOrderId");
                                String showTime = (String) XposedHelpers.callMethod(orderItem, "getShowTime");
                                @SuppressLint("SimpleDateFormat")
                                long showTimeMilli = TimeUtils.string2Millis(showTime, new SimpleDateFormat("支付时间：yyyy-MM-dd HH:mm:ss"));

                                LogUtils.i(orderId,showTimeMilli,lastOrderId,lasShowTimeMilli);
                                if (orderId.equals(lastOrderId)
                                        || showTimeMilli < lasShowTimeMilli) {
                                    //对取到的数据newWdShopTransBeans，进行处理。保存或发送到服务端。
                                    LogUtils.i("新的订单数据数量是" + newWdShopTransBeans.size());
                                    break;
                                }

                                //对获取到的单一订单数据对象进行读取，返回整理好的订单数据
                                WDShopTransBean wdShopTransBean = getWdShopTransBean(orderItem);
                                newWdShopTransBeans.add(wdShopTransBean);
                            }

                        } catch (Exception e) {
                            LogUtils.i(e.getMessage());
                        }
                    }
                });
    }

    /**
     * 对获取到的单一订单数据对象进行读取，返回整理好的订单数据
     *
     * @param objOrderItem 单条订单数据对象
     * @return 整理好的订单数据
     */
    private static WDShopTransBean getWdShopTransBean(Object objOrderItem) {
        Object objBuyerInfo = XposedHelpers.callMethod(objOrderItem, "getBuyerInfo");
//        Object objFxSellerInfo = XposedHelpers.callMethod(objOrderItem,"getFxSellerInfo");

        String buyerId = (String) XposedHelpers.callMethod(objBuyerInfo, "getBuyerId");
        String buyerName = (String) XposedHelpers.callMethod(objBuyerInfo, "getBuyerName");

//        String fxSellerAddress =(String) XposedHelpers.callMethod(objFxSellerInfo, "getFxSellerAddress");
//        long fxSellerId =(long) XposedHelpers.callMethod(objFxSellerInfo, "getFxSellerId");
//        String fxSellerName =(String) XposedHelpers.callMethod(objFxSellerInfo, "getFxSellerName");

        String buyerNote = (String) XposedHelpers.callMethod(objOrderItem, "getBuyerNote");
        String exhibitionJumpUrl = (String) XposedHelpers.callMethod(objOrderItem, "getExhibitionJumpUrl");
        String expressFee = (String) XposedHelpers.callMethod(objOrderItem, "getExpressFee");
        String imgHead = (String) XposedHelpers.callMethod(objOrderItem, "getImgHead");
        int loginSellerRole = (int) XposedHelpers.callMethod(objOrderItem, "getLoginSellerRole");
        String orderDesc = (String) XposedHelpers.callMethod(objOrderItem, "getOrderDesc");
        String orderId = (String) XposedHelpers.callMethod(objOrderItem, "getOrderId");
        int orderSource = (int) XposedHelpers.callMethod(objOrderItem, "getOrderSource");
        String phoneArgueDesc = (String) XposedHelpers.callMethod(objOrderItem, "getPhoneArgueDesc");
        String point = (String) XposedHelpers.callMethod(objOrderItem, "getPoint");
        int quantity = (int) XposedHelpers.callMethod(objOrderItem, "getQuantity");
        String refundStatusDesc = (String) XposedHelpers.callMethod(objOrderItem, "getRefundStatusDesc");
        String selFromValue = (String) XposedHelpers.callMethod(objOrderItem, "getSelFromValue");
        long sellerId = (long) XposedHelpers.callMethod(objOrderItem, "getSellerId");
        String showTime = (String) XposedHelpers.callMethod(objOrderItem, "getShowTime");
        int status = (int) XposedHelpers.callMethod(objOrderItem, "getStatus");
        String statusDesc = (String) XposedHelpers.callMethod(objOrderItem, "getStatusDesc");
        int statusHighLight = (int) XposedHelpers.callMethod(objOrderItem, "getStatusHighLight");

        List subOrderVOList = (List) XposedHelpers.callMethod(objOrderItem, "getSubOrderVOList");
        List<WDShopTransBean.WDShopSubOrderVOListBean> subOrderVOListBeans = new ArrayList<>();
        for (int i = 0; i < subOrderVOList.size(); i++) {
            Object objSubOrderItem = subOrderVOList.get(i);
            long itemId = (long) XposedHelpers.callMethod(objSubOrderItem, "getItemId");
            String itemName = (String) XposedHelpers.callMethod(objSubOrderItem, "getItemName");
            String itemSkuId = (String) XposedHelpers.callMethod(objSubOrderItem, "getItemSkuId");
            String itemSkuTitle = (String) XposedHelpers.callMethod(objSubOrderItem, "getItemSkuTitle");
            String price = (String) XposedHelpers.callMethod(objSubOrderItem, "getPrice");
            WDShopTransBean.WDShopSubOrderVOListBean subOrderVOListBean = new WDShopTransBean.WDShopSubOrderVOListBean(itemId, itemName, itemSkuId, itemSkuTitle, price);
            subOrderVOListBeans.add(subOrderVOListBean);
        }
        String totalPrice = (String) XposedHelpers.callMethod(objOrderItem, "getTotalPrice");

        WDShopTransBean wdShopTransBean = new WDShopTransBean(buyerId, buyerName, buyerNote, exhibitionJumpUrl, expressFee, imgHead
                , loginSellerRole, orderDesc, orderId, orderSource, phoneArgueDesc, point, quantity, refundStatusDesc, selFromValue
                , sellerId, showTime, status, statusDesc, statusHighLight, totalPrice, subOrderVOListBeans);

        LogUtils.i(GsonUtils.toJson(wdShopTransBean));
        return wdShopTransBean;
    }

    /**
     * hook 到订单管理里面进行中的View被创建的方法
     *
     * @param classLoader
     */
//    public static void hookTabOpenViewerOnCreated(ClassLoader classLoader) {
//        XposedHelpers.findAndHookMethod("com.koudai.weishop.order.page.list.tabs.open.OrderListTabOpenViewer"
//                , classLoader
//                , "onViewCreated"
//                , View.class
//                , Bundle.class
//                , new XC_MethodHook() {
//                    @Override
//                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
//                        super.beforeHookedMethod(param);
//                    }
//
//                    @Override
//                    protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
//                        super.afterHookedMethod(param);
//                        LogUtils.i("hook到了openView被创建的方法");
//                        ThreadUtils.executeByCpuWithDelay(new SimpleTaskSuccess<Object>() {
//                            @Override
//                            public void onSuccess(@Nullable Object result) {
//                                Object objOpenView = param.thisObject;
//                                Object objTabSlidingLayout = XposedHelpers.callMethod(objOpenView, "a", objOpenView);
//                                LogUtils.i(XposedHelpers.callMethod(objTabSlidingLayout, "getChildCount") + "ssss");
//                                final View viewLL = (View) XposedHelpers.callMethod(objTabSlidingLayout, "getChildAt", 0);
//                                final View viewTabFirst = (View) XposedHelpers.callMethod(viewLL, "getChildAt", 0);
//                                TextView tvTabFirstContent = (TextView) XposedHelpers.callMethod(viewTabFirst, "getChildAt", 1);
//                                int[] position = new int[2];
//                                viewTabFirst.getLocationInWindow(position);
//                                LogUtils.i("坐标", position[0], position[1], "描述内容=" + tvTabFirstContent.getText().toString());
//                                ThreadUtils.executeByFixedAtFixRate(4, new SimpleTaskSuccess<Object>() {
//                                    @Override
//                                    public void onSuccess(@Nullable Object result) {
//                                        LogUtils.i("开始执行自动点击");
//                                        viewTabFirst.performClick();
//                                    }
//                                }, 3, TimeUnit.SECONDS);
//                            }
//                        }, 2, TimeUnit.SECONDS);
//
//                    }
//                });
//    }

    /**
     * hook 到待发货那一行的view被创建的方法
     *
     * @param classLoader
     */
    public static void hookTabSlidingLayoutOnCreated(ClassLoader classLoader) throws Exception {
        boolean isCreated = false;
        XposedHelpers.findAndHookMethod("com.koudai.weishop.order.page.list.tabs.open.OrderListTabOpenViewer"
                , classLoader
                , "a"
                , classLoader.loadClass("com.koudai.weishop.order.page.list.tabs.open.OrderListTabOpenViewer")
                , new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        LogUtils.i("hook 到待发货那一行的view被创建的方法");
                        Object objTabSlidingLayout = param.getResult();
                        Object objLL = XposedHelpers.callMethod(objTabSlidingLayout, "getChildAt", 0);
                        final View viewTabFirst = (View) XposedHelpers.callMethod(objLL, "getChildAt", 0);
                        ThreadUtils.executeByFixedAtFixRate(4, new ThreadUtils.SimpleTask<Object>() {
                            @Nullable
                            @Override
                            public Object doInBackground() throws Throwable {
                                return null;
                            }

                            @Override
                            public void onSuccess(@Nullable Object result) {
                                LogUtils.i("开始执行自动点击");
                                viewTabFirst.performClick();
                            }
                        }, 3, TimeUnit.SECONDS);
                    }
                });
    }
}
